#!/bin/sh
#
# @license   http://www.gnu.org/licenses/gpl.html GPL Version 3
# @author    Ian Moore <imooreyahoo@gmail.com>
# @copyright Copyright (c) 2011 Ian Moore
#
# This file is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this file. If not, see <http://www.gnu.org/licenses/>.

set -e

. /etc/default/openmediavault
. /usr/share/openmediavault/scripts/helper-functions


DHCPD_CONFIG="/etc/dhcp/dhcpd.conf"
DHCPD_INIT="isc-dhcp-server"

# Enable/disable service
if [ "$(omv_config_get "//services/dhcpd/enable")" != "1" ]; then
	/etc/init.d/${DHCPD_INIT} stop
	update-rc.d ${DHCPD_INIT} disable
	exit 0
fi

xmlstarlet sel -t -m "//services/dhcpd" \
 -v "concat('option domain-name &quot;', domain-name, '&quot;;')" -n \
 -i "string-length(name-servers) > 0" \
 	-v "concat('option domain-name-servers ', name-servers, ';')" -n -b \
 -v "concat('option routers ', gateway, ';')" -n \
 -v "concat('default-lease-time ', default-lease-time, ';')" -n \
 -v "concat('max-lease-time ', default-lease-time, ';')" -n \
 -v "concat('subnet ', subnet, ' netmask ', netmask, ' {')" -n \
 -v "concat('    range ', first-ip, ' ', last-ip, ';')" -n \
 -i "string-length(wins-servers) > 0" \
	-v "concat('    option netbios-name-servers ', wins-servers, ';')" -n -b \
 -i "string-length(bootfile) > 0" \
    -v "concat('    filename &quot;', bootfile, '&quot;;')" -n -b \
${OMV_CONFIG_FILE} | xmlstarlet unesc > ${DHCPD_CONFIG}

# Reservations
index=$(omv_config_get_count "//services/dhcpd/reservations/reservation")
while [ ${index} -gt 0 ]
do

	xmlstarlet sel -t -m "//services/dhcpd/reservations/reservation[position()=${index}]" \
		-o "" -n \
		-v "concat('    host ', name, ' {')" -n \
		-v "concat('        hardware ethernet ', mac, ';')" -n \
		-i "string-length(ip) > 0" -v "concat('        fixed-address ', ip, ';')" -n -b \
      	-i "bootconfig = '..specify'" -v "concat('        filename &quot;', bootfile, '&quot;;')" -n -b \
      	-i "bootconfig = '..none'" -o "        deny booting;" -n -b \
		-o "    }" -n ${OMV_CONFIG_FILE} | xmlstarlet unesc >> ${DHCPD_CONFIG}

	index=$(( ${index} - 1 ))

done

echo '}' >>${DHCPD_CONFIG}

/etc/init.d/${DHCPD_INIT} restart
update-rc.d ${DHCPD_INIT} enable
update-rc.d ${DHCPD_INIT} defaults
